package com.todod.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.todod.common.util.BeanUtilEx;
import com.todod.common.util.EncryptUtil;
import com.todod.common.util.SnowflakeIdGenerator;
import com.todod.dto.UserDto;
import com.todod.entity.QueryEntry;
import com.todod.entity.ResUser;
import com.todod.exception.CustomException;
import com.todod.mapper.UserMapper;
import com.todod.model.User;
import com.todod.service.IDepartmentService;
import com.todod.service.IUserService;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author gsh
 * @since 2020-10-14
 */
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
	@Autowired
	private IDepartmentService iDepartmentService;

	@Override
	public User login(String userName, String password) {
		QueryWrapper<User> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("su_user_name", userName);
		queryWrapper.eq("su_password", EncryptUtil.encrypt(password));
		User user = getOne(queryWrapper);
		return user;
	}

	@Override
	public User getByUsernameAndPassword(String username, String password) {
		QueryWrapper<User> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("su_user_name", username);
		queryWrapper.eq("su_password", EncryptUtil.encrypt(password));

		User user = getOne(queryWrapper);
		return user;
	}

	@Override
	public User getByUsername(String username) {
		QueryWrapper<User> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("su_user_name", username);
		User user = getOne(queryWrapper);
		return user;
	}

	@Override
	public IPage<UserDto> getList(QueryEntry queryEntry) {
		Page<UserDto> page = new Page<>(queryEntry.getPage(), queryEntry.getLimit());
		UserMapper userMapper = this.getBaseMapper();
		IPage<UserDto> iPage = userMapper.getList(page, queryEntry);
		return iPage;
	}

	@Override
	public IPage<UserDto> getDnameList(QueryEntry queryEntry) {
		Page<UserDto> page = new Page<>(queryEntry.getPage(), queryEntry.getLimit());
		UserMapper userMapper = this.getBaseMapper();
		IPage<UserDto> iPage = userMapper.getDnameList(page, queryEntry);
		return iPage;
	}

	@Override
	public void saveData(Long _userId, ResUser resUser) {
		if (resUser.getId() == null) {
			User byLoginName = this.getByLoginName(resUser.getUserName(), resUser.getDepartid());
			if (byLoginName != null) {
				throw new CustomException("用户名在该部门下已存在");
			}

			User user = new User();
			try {
				BeanUtilEx.copyProperties(user, resUser);
			} catch (Exception e) {
				log.error("error", e);
				throw new CustomException("数据错误");
			}

			user.setId(SnowflakeIdGenerator.getId());
			user.setCreateTime(LocalDateTime.now());
			user.setPassword(EncryptUtil.encrypt(user.getPassword()));
			user.setCreateUserId(_userId);
			user.setState("2");

			this.save(user);

			resUser.setId(user.getId());
		} else {
			User user = getById(resUser.getId());

			user.setModifyUserId(_userId);
			user.setModifyTime(LocalDateTime.now());

			user.setNickName(resUser.getNickName());
			user.setRoleId(resUser.getRoleId());
			user.setDepartid(resUser.getDepartid());
			user.setEmail(resUser.getEmail());

			this.updateById(user);
		}
	}

	public User getByLoginName(String loginName, Long long1) {
		QueryWrapper<User> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("su_user_name", loginName);
		queryWrapper.eq("su_department_id", long1);
		User user = getOne(queryWrapper);
		return user;
	}

	@Override
	public void updateState(Long _userId, Long userId, String state) {
		User user = this.getById(userId);

		if (user == null)
			return;

		if (!user.getState().equals(state)) {
			user.setState(state);
			updateById(user);
		}
	}

	@Override
	public void editPasssWord(Long _userId, Long userId, String password) {
		User user = this.getById(userId);

		if (user == null)
			throw new CustomException("用户不存在");

		user.setPassword(EncryptUtil.encrypt(password));
		user.setModifyTime(LocalDateTime.now());
		user.setModifyUserId(_userId);

		updateById(user);
	}

	@Override
	public User getUserById(Long id) {
		return this.getById(id);
	}

	@Override
	public List<User> getAllUser() {
		QueryWrapper<User> wrapper = new QueryWrapper<User>();

		wrapper.select("su_id as id", "su_user_name as userName", "su_nick_name as nickName", "su_state as state");

		return list(wrapper);
	}

	@Override
	public List<User> getListByDepartmentIds(List<Long> did) {
		QueryWrapper<User> wrapper = new QueryWrapper<User>();

		wrapper.select("su_id as id", "su_user_name as userName", "su_nick_name as nickName", "su_state as state",
				"su_department_id as departid", "su_job_num as jobNum", "su_email as email",
				"su_create_time as createTime");

		wrapper.in("su_department_id", did);

		return list(wrapper);
	}

	@Override
	public List<User> getAllList() {
		QueryWrapper<User> wrapper = new QueryWrapper<User>();

		wrapper.select("su_id as id", "su_user_name as userName", "su_nick_name as nickName", "su_state as state",
				"su_department_id as departid", "su_job_num as jobNum", "su_email as email",
				"su_create_time as createTime");

		return list(wrapper);
	}

	@Override
	public List<User> getUserList(Long departid) {
		QueryWrapper<User> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("su_department_id", departid);

		return list(queryWrapper);
	}

}
